<template>
  <div class="recharge-container">
    <div class="recharge-header">
      <h1>账户充值</h1>
      <p class="recharge-subtitle">为您的账户添加余额，享受更多服务</p>
    </div>

    <div class="recharge-content">
      <el-card class="recharge-form-card">
        <template #header>
          <div class="card-header">
            <span>选择充值金额</span>
          </div>
        </template>
        <div class="recharge-amounts">
          <div
              v-for="amount in presetAmounts"
              :key="amount"
              :class="['amount-item', { active: selectedAmount === amount }]"
              @click="selectAmount(amount)"
          >
            ¥{{ amount }}
          </div>
          <div class="amount-item custom-amount"
               :class="{ active: isCustomAmount }"
               @click="toggleCustomAmount"
          >
            <el-input
                v-if="isCustomAmount"
                v-model.number="customAmount"
                type="number"
                placeholder="输入自定义金额"
                :min="10"
                :max="5000"
                :step="10"
                class="custom-amount-input"
                @input="handleCustomAmountChange"
            />
            <span v-else>自定义金额</span>
          </div>
        </div>

        <div class="payment-methods">
          <h3>选择支付方式</h3>
          <div
              v-for="method in paymentMethods"
              :key="method.value"
              :class="['payment-item', { active: selectedPaymentMethod === method.value }]"
              @click="selectPaymentMethod(method.value)"
          >
            <span class="payment-icon">{{ method.icon }}</span>
            <span class="payment-name">{{ method.name }}</span>
            <span class="payment-check" v-if="selectedPaymentMethod === method.value">✓</span>
          </div>
        </div>

        <div class="recharge-summary">
          <div class="summary-item">
            <span class="summary-label">充值金额：</span>
            <span class="summary-value">¥{{ currentAmount.toFixed(2) }}</span>
          </div>
          <div v-if="giftAmount > 0" class="summary-item">
            <span class="summary-label">赠送金额：</span>
            <span class="summary-value gift-amount">+¥{{ giftAmount.toFixed(2) }}</span>
          </div>
          <div class="summary-item total">
            <span class="summary-label">实际到账：</span>
            <span class="summary-value total-amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>

        <div class="recharge-actions">
          <el-button
              type="primary"
              size="large"
              @click="submitRecharge"
              :loading="accountStore.rechargeLoading"
              :disabled="currentAmount < 10 || !selectedPaymentMethod"
          >
            确认充值
          </el-button>
          <el-button
              size="large"
              @click="router.back()"
          >
            返回
          </el-button>
        </div>
      </el-card>

      <el-card class="recharge-rules">
        <template #header>
          <div class="card-header">
            <span>充值规则</span>
          </div>
        </template>
        <ul class="rules-list">
          <li>1. 账户余额可用于购买平台内的课程、测试和咨询服务</li>
          <li>2. 充值100元以上可享受10%的赠送金额</li>
          <li>3. 充值金额不支持提现，请根据实际需求充值</li>
          <li>4. 如有充值问题，请联系我们</li>
        </ul>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAccountStore } from '@/stores/account/account';
import { checkRechargeStatus } from '@/api/account/account';
import type { RechargeRequest, RechargeRecord } from '@/types/account/Account';
import PaymentQrCode from './PaymentQrCode.vue';

const router = useRouter();
const accountStore = useAccountStore();

// 支付弹窗相关状态
const showPaymentDialog = ref(false);
const paymentUrl = ref('');
const paymentExpireTime = ref('');
const paymentStatusCheckTimer: NodeJS.Timeout | null = null;
const currentRechargeNo = ref(''); // 添加这个变量来存储充值单号

const submitRecharge = async () => {
  try {
    // 1. 创建充值订单，获取支付信息
    const rechargeRequest: RechargeRequest = {
      amount: currentAmount.value,
      paymentMethod: selectedPaymentMethod.value as 'ALIPAY' | 'WECHAT'
    };
    
    const paymentInfo = await accountStore.recharge(rechargeRequest);
    
    // 2. 跳转到单独的支付页面，并传递金额参数
    if (paymentInfo && paymentInfo.recharge_no) {
      router.push({
        path: `/account/payment/${paymentInfo.recharge_no}`,
        query: { amount: currentAmount.value.toString() }
      });
    }
  } catch (error) {
    ElMessage.error('创建充值订单失败，请重试');
    console.error('充值失败:', error);
  }
};

// 预设充值金额
const presetAmounts = [50, 100, 200, 500, 1000, 2000];

// 支付方式
const paymentMethods = [
  { value: 'ALIPAY', name: '支付宝', icon:''},
  { value: 'WECHAT', name: '微信支付', icon:''}
];

// 状态
const selectedAmount = ref(100);
const customAmount = ref(0);
const isCustomAmount = ref(false);
const selectedPaymentMethod = ref<string | null>('ALIPAY');

/**
 * 选择预设金额
 */
const selectAmount = (amount: number) => {
  selectedAmount.value = amount;
  isCustomAmount.value = false;
};

/**
 * 切换自定义金额
 */
const toggleCustomAmount = () => {
  isCustomAmount.value = !isCustomAmount.value;
  if (isCustomAmount.value) {
    // 聚焦到输入框（需要在DOM更新后执行）
    setTimeout(() => {
      const input = document.querySelector('.custom-amount-input input') as HTMLInputElement;
      if (input) {
        input.focus();
      }
    }, 0);
  }
};

/**
 * 处理自定义金额变化
 */
const handleCustomAmountChange = () => {
  if (customAmount.value < 0) {
    customAmount.value = 0;
  } else if (customAmount.value > 10000) {
    customAmount.value = 10000;
  }
};

/**
 * 选择支付方式
 */
const selectPaymentMethod = (method: string) => {
  selectedPaymentMethod.value = method;
};

/**
 * 当前充值金额
 */
const currentAmount = computed(() => {
  return isCustomAmount.value && customAmount.value > 0
      ? customAmount.value
      : selectedAmount.value;
});

/**
 * 计算赠送金额
 */
const giftAmount = computed(() => {
  // 充值100元以上赠送10%
  if (currentAmount.value >= 100) {
    return Math.floor(currentAmount.value * 0.1);
  }
  return 0;
});

/**
 * 实际到账金额
 */
const totalAmount = computed(() => {
  return currentAmount.value + giftAmount.value;
});

// 修改checkPaymentStatus方法
const checkPaymentStatus = async (rechargeNo: string) => {
  // 每5秒检查一次支付状态，最多检查10分钟
  let checkCount = 0;
  const maxCheckCount = 120; 
  
  const timer = setInterval(async () => {
    checkCount++;
    if (checkCount >= maxCheckCount) {
      clearInterval(timer);
      ElMessage.warning('支付超时，请重新发起充值');
      showPaymentDialog.value = false;
      return;
    }
    
    try {
      // 调用实际的API检查支付状态
      const statusInfo = await checkRechargeStatus(rechargeNo);

      // 直接使用statusInfo，不需要再访问.data属性
      if (statusInfo.status === 'SUCCESS') {
        clearInterval(timer);
        showPaymentDialog.value = false;
        ElMessage.success('支付成功');
        await accountStore.fetchAccountBalance();
        router.push('/account');
      } else if (statusInfo.status === 'FAILED') {
        clearInterval(timer);
        showPaymentDialog.value = false;
        ElMessage.error('支付失败，请重新尝试');
      }
    } catch (error) {
      console.error('检查支付状态失败:', error);
    }
  }, 5000);
};

/**
 * 刷新支付二维码
 */
const refreshPayment = async () => {
  try {
    const rechargeRequest: RechargeRequest = {
      amount: currentAmount.value,
      paymentMethod: selectedPaymentMethod.value as 'ALIPAY' | 'WECHAT'
    };

    const response = await accountStore.recharge(rechargeRequest);
    // 修复：从data字段中获取实际数据
    const data = response.data || response;
    if (data && 'payment_url' in data && data.payment_url) {
      paymentUrl.value = data.payment_url;
      paymentExpireTime.value = data.expire_time || '';
    }
  } catch (error) {
    ElMessage.error('刷新失败，请重试');
    console.error('刷新支付二维码失败:', error);
  }
};
</script>

<style scoped>
.recharge-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.recharge-header {
  text-align: center;
  margin-bottom: 30px;
}

.recharge-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.recharge-subtitle {
  font-size: 16px;
  color: #909399;
}

.recharge-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

.recharge-form-card {
  border-radius: 12px;
}

.card-header {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.recharge-amounts {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin: 30px 0;
}

.amount-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  cursor: pointer;
  transition: all 0.3s;
}

.amount-item:hover {
  border-color: #667eea;
  color: #667eea;
}

.amount-item.active {
  border-color: #667eea;
  background-color: #f0f3ff;
  color: #667eea;
}

.custom-amount {
  border-style: dashed;
}

.custom-amount-input {
  width: 100%;
}

.payment-methods {
  margin: 30px 0;
}

.payment-methods h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.payment-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-item:hover {
  border-color: #667eea;
}

.payment-item.active {
  border-color: #667eea;
  background-color: #f0f3ff;
}

.payment-icon {
  font-size: 24px;
  margin-right: 16px;
}

.payment-name {
  flex: 1;
  font-size: 16px;
  color: #303133;
}

.payment-check {
  font-size: 20px;
  color: #667eea;
  font-weight: bold;
}

.recharge-summary {
  margin: 30px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 16px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-label {
  color: #606266;
}

.summary-value {
  font-weight: 500;
  color: #303133;
}

.gift-amount {
  color: #67c23a;
}

.summary-item.total {
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
  margin-top: 12px;
}

.total-amount {
  font-size: 20px;
  color: #667eea;
}
</style>